package com.example.threadblock;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author zhanghui
 * @date 2021/11/30 14:22
 */
public class JavaFutureDemo {
    public static final int SLEEP_TIME = 500;

    static class HotWaterJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                System.out.println("洗好水壶");
                System.out.println("灌上凉水");
                Thread.sleep(SLEEP_TIME);
                System.out.println("放在火上");
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
                System.out.println("** 烧水-Thread 异常被中断");
                return false;
            }
            System.out.println("水开了");
            return true;
        }
    }

    static class WashJob implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                System.out.println("洗茶壶");
                System.out.println("洗茶杯");
                Thread.sleep(SLEEP_TIME);
                System.out.println("拿茶叶");
                Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
                System.out.println("$$ 清洗-Thread 异常被中断");
                return false;
            }
            System.out.println("洗完了");
            return false;
        }
    }

    public static void drinkTea(boolean waterHotStatus, boolean washStatus) {
        if (!waterHotStatus) {
            System.out.println("烧水失败");
        } else if (!washStatus) {
            System.out.println("清洗失败");
        } else {
            System.out.println("泡茶喝");
        }
    }

    public static void main(String[] args) {
        Callable<Boolean> waterHotJob = new HotWaterJob();
        FutureTask<Boolean> hTask = new FutureTask<>(waterHotJob);
        Thread waterThread = new Thread(hTask, "** 烧水-Thread");

        Callable<Boolean> washJob = new WashJob();
        FutureTask<Boolean> wTask = new FutureTask<>(washJob);
        Thread washThread = new Thread(wTask, "$$ 清洗-Thread");

        waterThread.start();
        washThread.start();

        try {
            Boolean aBoolean = hTask.get();
            Boolean aBoolean1 = wTask.get();
            drinkTea(aBoolean, aBoolean1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
